import React, { useState } from 'react';
import { Box, Typography, TextField } from '@mui/material';
import { TreeView } from '@mui/lab';
import { styled } from '@mui/material/styles';
import { useDispatch, useSelector } from 'react-redux';
import { selectInstances } from '../../redux/slices/generalSlice';
import { experimentLabelColor } from '../../theme';
import ControlPanelTreeItem from './ControlPanelTreeItem';
import { TreeItemArrowRightIcon, TreeItemArrowDownIcon } from './NetPyNEIcons';

const StyledTreeView = styled(TreeView)(() => ({
  '& ul': {
    position: 'relative',
    '&::before': {
      content: '""',
      height: 'calc(100% - 1.1rem)',
      width: '0.0625rem',
      position: 'absolute',
      left: '-0.65rem',
      borderRadius: '3.125rem',
      top: '0rem',
      backgroundImage:
        'url("data:image/svg+xml,%3Csvg width=\'1\' height=\'8\' viewBox=\'0 0 1 8\' fill=\'none\' xmlns=\'http://www.w3.org/2000/svg\'%3E%3Cpath d=\'M0 0H1V8H0V0Z\' fill=\'%23989898\'/%3E%3C/svg%3E")',
      backgroundRepeat: 'repeat',
    },
    '& .MuiTreeItem-root': {
      position: 'relative',
      '&::before': {
        content: '""',
        height: '0.875rem',
        width: '1.4375rem',
        backgroundImage:
          'url("data:image/svg+xml,%3Csvg width=\'12\' height=\'6\' viewBox=\'0 0 12 6\' fill=\'none\' xmlns=\'http://www.w3.org/2000/svg\'%3E%3Cpath d=\'M6 6C2.68629 6 0 3.31371 0 0H1C1 2.80391 3.19609 5 6 5V6Z\' fill=\'%23989898\'/%3E%3Cpath d=\'M6 5H11.5C11.7761 5 12 5.22386 12 5.5C12 5.77614 11.7761 6 11.5 6H6V5Z\' fill=\'%23989898\'/%3E%3C/svg%3E")',
        position: 'absolute',
        top: '0.5rem',
        backgroundRepeat: 'no-repeat',
        left: '-0.65rem',
      },
      '&:hover': {
        background: 'transparent',
      },
      '&:focus > .MuiTreeItem-content': {
        backgroundColor: 'transparent',
      },
    },
  },
}));

interface ExperimentControlPanelProps {
  modelState?: string;
  [key: string]: any;
}

/**
 * ExperimentControlPanel Component
 * Control panel for experiment instances visualization
 * Placeholder implementation - ControlPanelTreeItem component needed
 */
const ExperimentControlPanel: React.FC<ExperimentControlPanelProps> = ({
  modelState,
  ...otherProps
}) => {
  const dispatch = useDispatch();
  const instances = useSelector((state: any) => state.general?.instances || []);
  const [filter, setFilter] = useState('');

  const onNodeSelect = (nodeId: string): void => {
    dispatch(selectInstances({ instances, selectedInstances: [nodeId] }));
  };

  const onVisibilityClick = (event: React.MouseEvent, nodeId: string): void => {
    console.log(`Visibility of node with id of ${nodeId} clicked.`);
  };

  // Placeholder for tree item generation
  // This needs ControlPanelTreeItem component to be created
  const getTreeItemsFromData = (treeItems: any[]): React.ReactNode[] => {
    if (!Array.isArray(treeItems)) return [];
    
    return treeItems.map((treeItemData: any) => {
      let children: React.ReactNode[] = [];
      if (treeItemData.getChildren && treeItemData.getChildren().length > 0) {
        children = getTreeItemsFromData(treeItemData.getChildren());
      }

      return (
        <ControlPanelTreeItem
          key={treeItemData.id || treeItemData.getPath?.()}
          nodeId={treeItemData.getPath?.() || treeItemData.id}
          label={treeItemData.id || 'Unknown'}
          type={treeItemData.getType?.()?.getId?.() || 'unknown'}
          onNodeSelect={onNodeSelect}
          onVisibilityClick={onVisibilityClick}
          disableRandom={children.length === 0}
        >
          {children}
        </ControlPanelTreeItem>
      );
    });
  };

  return (
    <>
      <Box className="header" sx={{ mb: 2 }}>
        <Typography variant="h6" sx={{ color: experimentLabelColor, fontWeight: 'bold' }}>
          Instances
        </Typography>
      </Box>
      <TextField
        fullWidth
        variant="filled"
        label="Filter instances"
        value={filter}
        onChange={(e) => setFilter(e.target.value)}
        sx={{ mb: 2 }}
      />
      <StyledTreeView
        defaultCollapseIcon={<TreeItemArrowDownIcon />}
        defaultExpandIcon={<TreeItemArrowRightIcon />}
        defaultEndIcon={<Box sx={{ width: 24 }} />}
      >
        {getTreeItemsFromData(instances)}
      </StyledTreeView>
    </>
  );
};

export default ExperimentControlPanel;

